package org.jeecg.modules.demo.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.demo.allvipcard.entity.AllVipcard;
import org.jeecg.modules.demo.app.mapper.AppMapper;
import org.jeecg.modules.demo.app.service.AppService;
import org.jeecg.modules.demo.basejobserveitem.entity.BaseJobServeItem;
import org.jeecg.modules.demo.basejobserveitem.service.IBaseJobServeItemService;
import org.jeecg.modules.demo.basemembervipcoupon.entity.BaseMemberVipCoupon;
import org.jeecg.modules.demo.basemembervipcoupon.service.IBaseMemberVipCouponService;
import org.jeecg.modules.demo.baseorde.entity.BaseOrder;
import org.jeecg.modules.demo.baseorde.service.IBaseOrderService;
import org.jeecg.modules.demo.baseorderproject.entity.BaseOrderProject;
import org.jeecg.modules.demo.baseorderproject.service.IBaseOrderProjectService;
import org.jeecg.modules.demo.baseorderservicewriteoff.entity.BaseOrderServiceWriteoff;
import org.jeecg.modules.demo.baseorderservicewriteoff.service.IBaseOrderServiceWriteoffService;
import org.jeecg.modules.demo.baseselfordercommodity.entity.BaseSelfOrderCommodity;
import org.jeecg.modules.demo.baseselfordercommodity.service.IBaseSelfOrderCommodityService;
import org.jeecg.modules.demo.commoditymanagement.entity.CommodityManagement;
import org.jeecg.modules.demo.commoditymanagement.service.ICommodityManagementService;
import org.jeecg.modules.demo.instoragedetail.entity.InStorageDetail;
import org.jeecg.modules.demo.instoragedetail.service.IInStorageDetailService;
import org.jeecg.modules.demo.instoragemain.entity.InStorageMain;
import org.jeecg.modules.demo.instoragemain.service.IInStorageMainService;
import org.jeecg.modules.demo.projectmanagement.entity.ProjectManagement;
import org.jeecg.modules.demo.projectmanagement.service.IProjectManagementService;
import org.jeecg.modules.demo.reserverecord.entity.ReserveRecord;
import org.jeecg.modules.demo.storageoutindetail.entity.StorageOutinDetail;
import org.jeecg.modules.demo.storageoutindetail.service.IStorageOutinDetailService;
import org.jeecg.modules.demo.storeproject.entity.StoreProject;
import org.jeecg.modules.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Date;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AppServiceImpl implements AppService {

    @Autowired
    private AppMapper appMapper;
    @Autowired
    private ICommodityManagementService commodityManagementService;
    @Autowired
    private IBaseOrderService baseOrderService;
    @Autowired
    private IBaseOrderProjectService baseOrderProjectService;
    @Autowired
    private IBaseMemberVipCouponService baseMemberVipCouponService;
    @Autowired
    private IInStorageMainService inStorageMainService;
    @Autowired
    private IInStorageDetailService inStorageDetailService;
    @Autowired
    private IStorageOutinDetailService storageOutinDetailService;
    @Autowired
    private IBaseSelfOrderCommodityService baseSelfOrderCommodityService;
    @Autowired
    private IBaseJobServeItemService baseJobServeItemService;
    @Autowired
    private IBaseOrderServiceWriteoffService baseOrderServiceWriteoffService;
    @Autowired
    private IProjectManagementService projectManagementService;
    @Override
    public List<Map<String, Object>> listMemberProject(Map<String, Object> map) {
        return appMapper.listMemberProject(map);
    }

    @Override
    public List<Map<String, Object>> listMemberCommodity(Map<String, Object> map) {

        List<Map<String, Object>> list = appMapper.listMemberCommodity(map);
        List<Map<String, Object>> result = new ArrayList<>();

        list.forEach(m -> {
            List<BaseSelfOrderCommodity> commodityList = baseSelfOrderCommodityService.list(new QueryWrapper<BaseSelfOrderCommodity>().eq("order_id", String.valueOf(m.get("id"))));
            if (commodityList.size() == 0) {
                return;
            }
            List<Map<String, Object>> commodityList1 = commodityList.stream().map(c -> {
                Map<String, Object> m1 = ToolsUtils.objectToMap(c);
                BigDecimal totalPrice = m1.get("totalPrice") == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(m1.get("totalPrice")));
                BigDecimal preferAmount = m1.get("preferAmount") == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(m1.get("preferAmount")));
                m1.put("realPrice", totalPrice.subtract(preferAmount));
                String status1 = String.valueOf(m.get("status"));
                if ("0".equals(status1)) {
                    m1.put("statusName", "未自提");
                } else if ("1".equals(status1)) {
                    m1.put("statusName", "已自提");
                }
                return m1;
            }).collect(Collectors.toList());
            m.put("commodityList", commodityList1);
            result.add(m);
        });

        return result;
    }

    @Override
    public int updatePraiseNumById(int num, String id) {
        return appMapper.updatePraiseNumById(num, id);
    }

    @Override
    public int updateForwardNumById(int num, String id) {
        return appMapper.updateForwardNumById(num, id);
    }

    @Override
    public List<AllVipcard> getCard(String storeId, String cardId) {
        return appMapper.getCard(storeId, cardId);
    }

//    @Override
//    public List<ReserveRecord> listByEmployeeDate(String storeId, String projectId, LocalDate orderDay, String empolyeeId) {
//        return appMapper.listByEmployeeDate(storeId,projectId,orderDay,empolyeeId);
//    }

    @Override
    public List<ReserveRecord> listByDate(String storeId, String projectId, Date orderDay) {
        return appMapper.listByDate(storeId, projectId, orderDay);
    }

    @Override
    public List<ReserveRecord> listByEmployeeDate(String storeId, String projectId, Date startDay, Date endDay, String employeeId) {
        return appMapper.listByEmployeeDatePeriod(storeId, projectId, startDay, endDay, employeeId);
    }


    @Override
    public ReserveRecord queryReserveRecordById(String detailId) {
        return appMapper.queryReserveRecordById(detailId);
    }

    @Override
    public List<StoreProject> listStoreProjects(String storeId) {
        return appMapper.listStoreProjects(storeId);
    }


    @Override
    public List<ReserveRecord> listByEmployeeDate(String storeId, String projectId, LocalDate orderDay, String empolyeeId) {
        return appMapper.listByEmployeeDate(storeId, projectId, orderDay, empolyeeId);
    }

    @Scheduled(cron = "* */2 * * * ?")
    public void cancelOrder() {
        log.info("扫描超时线上订单");
        List<BaseOrder> list = appMapper.scanOvertimeOrder();

        for (BaseOrder order : list) {
            Map<String, Object> map = (Map<String, Object>) JSON.parse(order.getOrderJsonStr());
            String storeId = map.get("storeId") == null ? null : String.valueOf(map.get("storeId"));
            String memberId = map.get("memberId") == null ? null : String.valueOf(map.get("memberId"));
            String totalAmount = map.get("totalAmount") == null ? null : String.valueOf(map.get("totalAmount"));
            String totalDiscountAmount = map.get("totalDiscountAmount") == null ? null : String.valueOf(map.get("totalDiscountAmount"));
            String realAmount = map.get("realAmount") == null ? null : String.valueOf(map.get("realAmount"));
            List<Map<String, Object>> commodityList = (List<Map<String, Object>>) map.get("commodityList");
            String useMemberDiscountStr = map.get("useMemberDiscount") == null ? null : String.valueOf(map.get("useMemberDiscount"));
            String memberDiscountStr = map.get("memberDiscount") == null ? null : String.valueOf(map.get("memberDiscount"));
            List<Map<String, Object>> couponList = map.get("couponList") == null ? new ArrayList<>() : (List<Map<String, Object>>) map.get("couponList");
            String remark = map.get("remark") == null ? null : String.valueOf(map.get("remark"));
            BigDecimal realAmountDecimal = new BigDecimal(realAmount);
            boolean useMemberDiscount = "1".equals(useMemberDiscountStr);
            BigDecimal memberDiscount = memberDiscountStr == null ? BigDecimal.TEN : new BigDecimal(memberDiscountStr);

            for (Map<String, Object> m : couponList) {
                String id = m.get("id") == null ? null : String.valueOf(m.get("id"));
                String numStr = m.get("num") == null ? "0" : String.valueOf(m.get("num"));
                int num = Integer.parseInt(numStr);
                BaseMemberVipCoupon bmvc = baseMemberVipCouponService.getById(id);
                bmvc.setNum(bmvc.getNum() + num);
                baseMemberVipCouponService.updateById(bmvc);
            }

            // 入库记录明细
            List<InStorageDetail> inStorageDetailList = new ArrayList<>();
            // 出入库明细
            List<StorageOutinDetail> storageOutinDetailList = new ArrayList<>();

            for (Map<String, Object> m : commodityList) {
                String id = m.get("id") == null ? null : String.valueOf(m.get("id"));
                String type = m.get("type") == null ? null : String.valueOf(m.get("type"));
                String countStr = m.get("count") == null ? "0" : String.valueOf(m.get("count"));
                BigDecimal count = new BigDecimal(countStr);
                String name = m.get("name") == null ? "0" : String.valueOf(m.get("name"));
                String specification = m.get("specification") == null ? "0" : String.valueOf(m.get("specification"));
                String price = m.get("price") == null ? "0" : String.valueOf(m.get("price"));
                String totalPrice = m.get("totalPrice") == null ? "0" : String.valueOf(m.get("totalPrice"));
                String discountAmount = m.get("discountAmount") == null ? "0" : String.valueOf(m.get("discountAmount"));
                String free = m.get("free") == null ? "0" : String.valueOf(m.get("free"));
                String pic = m.get("pic") == null ? "0" : String.valueOf(m.get("pic"));
                String staffId = m.get("staffId") == null ? "0" : String.valueOf(m.get("staffId"));

                BigDecimal totalPriceDecimal = new BigDecimal(totalPrice);
                BigDecimal discountAmountDecimal = new BigDecimal(discountAmount);
                BigDecimal realTotalPrice = totalPriceDecimal.subtract(discountAmountDecimal);

                if ("1".equals(type)) {
                    // ------------------------- 商品 -------------------------
                    CommodityManagement cm = commodityManagementService.getById(id);
                    cm.setInventory(cm.getInventory() + count.intValue());
                    commodityManagementService.updateById(cm);

                    // 入库记录明细
                    InStorageDetail inStorageDetail = new InStorageDetail();
                    inStorageDetail.setCommodityId(id);
                    inStorageDetail.setCommodityName(cm.getTradeName());
                    inStorageDetail.setCommoditySpecs(cm.getSpecification());
                    inStorageDetail.setInQty(count.intValue());
                    inStorageDetail.setStoreId(storeId);
                    inStorageDetailList.add(inStorageDetail);

                    // 出入库明细
                    StorageOutinDetail storageOutinDetail = new StorageOutinDetail();
                    storageOutinDetail.setCommodityName(cm.getTradeName());
                    storageOutinDetail.setCommodityId(cm.getId());
                    storageOutinDetail.setOperateType("入库操作");
                    storageOutinDetail.setOutinQty(count.intValue());
                    storageOutinDetail.setRemainQty(cm.getInventory());
                    storageOutinDetail.setBillTime(new java.util.Date());
                    storageOutinDetail.setOperator("线上订单超时");
                    storageOutinDetail.setStoreId(storeId);
                    storageOutinDetailList.add(storageOutinDetail);
                } else {
                    // ------------------------- 项目 -------------------------
                }
            }
            if (inStorageDetailList.size() > 0) {
                InStorageMain inStorageMain = new InStorageMain();
                String billNo = ToolsUtils.getBillNo("IS");
                inStorageMain.setBillNo(billNo);
                inStorageMain.setInType("13");
                inStorageMain.setBillTime(new java.util.Date());
                inStorageMain.setPreparer("线上订单超时");
                inStorageMain.setStoreId(storeId);
                inStorageMainService.save(inStorageMain);
                for (InStorageDetail inStorageDetail : inStorageDetailList) {
                    inStorageDetail.setMainId(inStorageMain.getId());
                    inStorageDetail.setBillNo(billNo);
                    inStorageDetail.setOutinType("13");
                    inStorageDetailService.save(inStorageDetail);
                }
                for (StorageOutinDetail storageOutinDetail : storageOutinDetailList) {
                    storageOutinDetail.setBillNo(billNo);
                    storageOutinDetail.setOutinType("13");
                    storageOutinDetailService.save(storageOutinDetail);
                }
            }

            order.setOrderStatus("3");
            baseOrderService.updateById(order);
        }
    }

    @Scheduled(cron = "* */2 * * * ?")
    public void cancelVipOrder() {
        log.info("扫描超时贵宾卡支付订单");
        appMapper.updateOvertimeVipOrder();
    }

    @Scheduled(cron = "0 0 * * * ?")
    public void setNewMemberToOld() {
        log.info("扫描24小时以上的新会员");
        //appMapper.setNewMemberToOld();
    }

    @Scheduled(cron = "0 */10 * * * ?")
    public void scanTimesCardOrder() {
        log.info("扫描次卡订单");
        List<BaseOrderProject> list = baseOrderProjectService.list(new QueryWrapper<BaseOrderProject>().eq("is_valid", "1"));
        for (BaseOrderProject p : list){
            if (p.getTimingWay() == null){
                String projectId = p.getProjectId();
                ProjectManagement project = projectManagementService.getById(projectId);
                p.setTimingWay(project.getTimingWay());
                p.setIndate(project.getIndate());
                baseOrderProjectService.updateById(p);
            }
        }
        list = baseOrderProjectService.list(new QueryWrapper<BaseOrderProject>().eq("is_valid", "1"));
        for (BaseOrderProject p : list){
            if (p.getValidateTime() != null){
                java.util.Date validateTime = p.getValidateTime();
                java.util.Date date =new java.util.Date();
                if (validateTime.getTime() < date.getTime()){
                    p.setIsValid("0");
                    p.setInvalidStatus("2");
                    baseOrderProjectService.updateById(p);
                }
            }else {
                String projectId = p.getProjectId();
                ProjectManagement project = projectManagementService.getById(projectId);
                //计时方式 1-gm-从购买开始 2- 核销，从第一次消费开始
               /* if ("1".equals(project.getTimingWay())) {
                    int indate = Integer.valueOf(project.getIndate()).intValue();
                    p.setIndate(project.getIndate());
                    java.util.Date createTime = p.getCreateTime();
                    long time = createTime.getTime() + (long) indate * 1000 * 3600 * 24;
                    java.util.Date date = new Date(time);
                    p.setValidateTime(date);
                    baseOrderProjectService.updateById(p);
                } else if ("2".equals(project.getTimingWay())) {
                    int indate = Integer.valueOf(project.getIndate()).intValue();

                    p.setIndate(project.getIndate());
                    List<BaseOrderServiceWriteoff> slist = baseOrderServiceWriteoffService.list(new QueryWrapper<BaseOrderServiceWriteoff>().eq("order_id", p.getOrderId()).eq("order_project_id", p.getProjectId()));
                    java.util.Date date = new java.util.Date();
                    for (BaseOrderServiceWriteoff baseOrderServiceWriteoff : slist) {
                        java.util.Date createTime = baseOrderServiceWriteoff.getCreateTime();
                        if (createTime != null) {
                            if (createTime.getTime() < date.getTime()) {
                                date = createTime;
                            }
                        }
                    }
                    long time = date.getTime() + (long) indate * 1000 * 3600 * 24;
                    java.util.Date validateTime = new java.util.Date(time);
                    p.setValidateTime(validateTime);
                    baseOrderProjectService.updateById(p);
                }*/
            }

            if ("1".equals(p.getIsValid())) {
                List<BaseJobServeItem> list1 = baseJobServeItemService.list(new QueryWrapper<BaseJobServeItem>().eq("store_id", p.getStoreId()).eq("project_id", p.getProjectId()));
                int times = 0;
                for (BaseJobServeItem item : list1) {
                    times = times + item.getServeNum();
                }

                List<BaseOrderServiceWriteoff> slist = baseOrderServiceWriteoffService.list(new QueryWrapper<BaseOrderServiceWriteoff>().eq("store_id", p.getStoreId()).eq("order_project_id", p.getOrderId()));
                if (times > 0 && times == slist.size()) {
                    p.setIsValid("0");
                    p.setInvalidStatus("1");
                    baseOrderProjectService.updateById(p);
                }
            }
        }
        log.info("扫描次卡订单结束");
    }

}
